package com.aitou.mrylive.presentation.ui.room;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.facebook.drawee.view.SimpleDraweeView;
import com.github.magiepooh.recycleritemdecoration.ItemDecorations;
import com.google.gson.Gson;
import com.jakewharton.rxbinding.view.RxView;
import com.aitou.mrylive.BeautyLiveApplication;
import com.aitou.mrylive.R;
import com.aitou.mrylive.data.bean.AnchoBean;
import com.aitou.mrylive.data.bean.Danmu;
import com.aitou.mrylive.data.bean.gift.SendGiftAction;
import com.aitou.mrylive.data.bean.me.UserInfo;
import com.aitou.mrylive.data.bean.websocket.AudienceInfo;
import com.aitou.mrylive.data.bean.websocket.ErrorMsg;
import com.aitou.mrylive.data.bean.websocket.LightHeartMsg;
import com.aitou.mrylive.data.bean.websocket.LiveAudienceListMsg;
import com.aitou.mrylive.data.bean.websocket.RoomPublicMsg;
import com.aitou.mrylive.data.bean.websocket.SendGiftMsg;
import com.aitou.mrylive.data.bean.websocket.SystemMsg;
import com.aitou.mrylive.data.bean.websocket.SystemWelcome;
import com.aitou.mrylive.data.bean.websocket.UserPublicMsg;
import com.aitou.mrylive.data.bean.websocket.WsLoginMsg;
import com.aitou.mrylive.data.bean.websocket.WsLoginOutMsg;
import com.aitou.mrylive.data.bean.websocket.WsRoomManageRequest;
import com.aitou.mrylive.data.repository.SourceFactory;
import com.aitou.mrylive.data.websocket.SocketConstants;
import com.aitou.mrylive.data.websocket.WebSocketService;
import com.aitou.mrylive.data.websocket.WsListener;
import com.aitou.mrylive.data.websocket.WsObjectPool;
import com.aitou.mrylive.domain.LocalDataManager;
import com.aitou.mrylive.nohttp.HttpListener;
import com.aitou.mrylive.presentation.ui.base.BaseActivity;
import com.aitou.mrylive.presentation.ui.base.BaseFragment;
import com.aitou.mrylive.presentation.ui.base.BaseUiInterface;
import com.aitou.mrylive.presentation.ui.base.recycler.SimpleRecyclerAdapter;
import com.aitou.mrylive.presentation.ui.base.recycler.SimpleRecyclerHolder;
import com.aitou.mrylive.presentation.ui.chatting.DropDownListView;
import com.aitou.mrylive.presentation.ui.chatting.RecordVoiceButton;
import com.aitou.mrylive.presentation.ui.chatting.SortConvList;
import com.aitou.mrylive.presentation.ui.chatting.utils.BitmapLoader;
import com.aitou.mrylive.presentation.ui.chatting.utils.DialogCreator;
import com.aitou.mrylive.presentation.ui.chatting.utils.Event;
import com.aitou.mrylive.presentation.ui.chatting.utils.HandleResponseCode;
import com.aitou.mrylive.presentation.ui.chatting.utils.IdHelper;
import com.aitou.mrylive.presentation.ui.room.gift.IAnimController;
import com.aitou.mrylive.presentation.ui.room.gift.IGiftAnimPlayer;
import com.aitou.mrylive.presentation.ui.room.gift.LocalAnimQueue;
import com.aitou.mrylive.presentation.ui.room.prvmsg.MsgListRoomAdapter;
import com.aitou.mrylive.presentation.ui.room.prvmsg.PrvListAdapter;
import com.aitou.mrylive.presentation.ui.room.pubmsg.PublicChatAdapter;
import com.aitou.mrylive.presentation.ui.widget.UserInfoDialog;
import com.aitou.mrylive.presentation.ui.widget.heardAnim.HeartAnim;
import com.aitou.mrylive.util.Const;
import com.aitou.mrylive.util.L;
import com.aitou.mrylive.util.TimingLogger;
import com.aitou.mrylive.util.danmu.DanmuControl;
import com.aitou.mrylive.util.roomanim.CarView;
import com.aitou.mrylive.util.roomanim.FireworksImagerView;
import com.aitou.mrylive.util.roomanim.GenView;
import com.aitou.mrylive.util.roomanim.GitfSpecialsStop;
import com.aitou.mrylive.util.roomanim.PlaneImagerView;
import com.aitou.mrylive.util.roomanim.ShipView;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.content.ImageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.enums.ContentType;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.api.BasicCallback;
import de.greenrobot.event.EventBus;
import master.flame.danmaku.controller.IDanmakuView;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.ui.widget.DanmakuView;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * 房间页面的基类，用于抽象三种情况下的公共操作。
 *
 * @author Muyangmin
 * @since 1.0.0
 */
public abstract class RoomFragment extends BaseFragment implements RoomActivity.HasInputLayout, HttpListener<Bitmap>, BaseUiInterface, GitfSpecialsStop {

    private static final String MsgIDs = "msgIDs";
    private static final String NICKNAME = "nickname";
    private static final int REQUEST_CODE_TAKE_PHOTO = 4;
    private static final int RESULT_CODE_SELECT_PICTURE = 8;
    private static final int RESULT_CODE_FRIEND_INFO = 17;
    private static final int REFRESH_LAST_PAGE = 0x1023;

    private UIHandler mUIHandler = new UIHandler(this);
    private boolean mIsSingle = true;
    private boolean mShowSoftInput = false;
    private MsgListRoomAdapter mChatAdapter;
    private Conversation mConv;
    private MyReceiver receiver;
    private cn.jpush.im.android.api.model.UserInfo mMyInfo;
    private String draft;
    private String mTargetId;
    private String mTargetAppKey;
    private String mPhotoPath = null;

    Window mWindow;
    InputMethodManager mImm;

    private static String TAG = RoomFragment.class.getSimpleName();
    private NetworkReceiver mReceiver;
    private Activity mcontext;
    private BackgroundHandler mBackgroundHandler;
    private HandlerThread mThread;
    private static final int REFRESH_CONVERSATION_LIST = 0x3000;
    private static final int UNREAD= 0x99999;
    private static final int READ= 0x99997;
    protected final String TIMING_LOG_TAG = "timing";
    /**
     * 用于监测启动和退出时的执行时间，为避免多次创建对象，一个Fragment实例仅使用一个对象。
     * 父类和子类都需要在启动和退出方法中调用reset和dump，以确保每次打点的消息一定能被dump。
     */
    protected final TimingLogger timingLogger = new TimingLogger(TIMING_LOG_TAG, "Not Initialized");

    protected WebSocketService wsService;
    private String mRoomId;

    protected TextView tvGold, mPrvChat, tvChatName,mChatTitle,unRead,newMsg;
    private ImageButton ibBack, ibToBack, ibSysBack;
    private AnchoBean mAnchoBean;
    private Button mSendMsgBtn;

    private IAnimController localGiftController;

    public LinearLayout llOperationBar;
    public LinearLayout llChatBar, llIn, llSys;
    public LinearLayout llHeader, mRankLay;
    public RelativeLayout rlPrvChat;
    public NestedScrollView mRoomScroll;
    public EditText edtChatContent, mChatInputEt;
    private PublicChatAdapter publicChatAdapter;

    private DropDownListView mChatListView;

    private ListView roomShow;
    private List<Conversation> mDatas = new ArrayList<Conversation>();
    private PrvListAdapter mListAdapter;
    private Dialog mDialog;

    protected RecyclerView recyclerPublicChat;
    private HeartAnim mHeartAnim;
    protected RelativeLayout mRoot;
    /**
     * 实时在线观看人数。
     */
    protected TextView tvOnlineCount;
    private RecyclerView recyclerAudienceList;
    private AudienceAdapter audienceAdapter;

    protected int[] heartColorArray;
    private int defaultColorIndex;

    private boolean isKicked;

    private boolean isRoomAdmin = false;
    //    创建一个用户发送信息对象用来直接显示
    private UserPublicMsg userPublicMsg;
    //    创建一个布尔值判断只对userPublicMsg进行一次设置
    private boolean initUserPublicMsg = false;
    //    等级
    private int publicMsgLevel;
    //    id
    private String publicMsgId;
    //    name
    private String publicMsgName;
    // 主播的id
    private String mAnchorId;

    private TextView mWaterId, mWaterDate;
    //    弹幕开关
    private boolean danmuopenis = false;
    //      根据弹幕开关显示对应的弹幕开关样式
    private LinearLayout danmu_layout_close, danmu_layot_open;
    //      弹幕view
    public DanmakuView mDanmakuView;
    //   弹幕分析器
    public BaseDanmakuParser mParser;
    //    弹幕context
    public DanmakuContext mContext;


    //    弹幕对象
    public Danmu danmu;
    //  头像请求
    Request<Bitmap> request;

    //    可能在上一个红包还没打开，下一个红包就来了，所以为了防止下一个红包还能使用，我们这里讲红包储存到一个集合里
    private List<SendGiftMsg> hongbaolist;

    //    通过socket监听主播退出
    public boolean isloginout = false;
    //    头像右下角的小角角
    private int[] starticon;

    //    头像右下角的星星
    private ImageView iconstart;

    //    头像栏的关注
    public TextView toptabstart;
//   小伙伴
    public RelativeLayout friendLayout;
//    关闭小伙伴
    public Button mFriendClose;

//    礼物动画
    private RelativeLayout animLayout;
//    烟花
    private FireworksImagerView fireworks;
//    灰机
    private PlaneImagerView plane;
//    汽车
    private CarView car;
//    船
    private ShipView ship;
//    移动
    public RelativeLayout moveLayout;
//    记录大礼物
    private List<Integer> gitfSpecials;
//    大礼物动画结束
    private boolean isgiftend=true;
//    记录死亡
    private boolean isdeas=false;
//    砖石
    private GenView gen;
    private boolean r=false;
    private boolean f=false;
    private String mMyName,mMyPassword;
    private ServiceConnection wsConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("mrl", "Service connected.");
            wsService = ((WebSocketService.ServiceBinder) service).getService();
            wsService.sendRequest(WsObjectPool.newLoginRequest(mRoomId));
            initWsListeners();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("mrl", "Service disconnected.");
        }
    };

    /**
     * @param roomId 房间号
     *               拉流地址。
     */
    public static String getPlayerUrl(String roomId) {
//        return BuildConfig.PLAYER_BASE_URL + roomId;
        return "rtmp://pili-live-rtmp.xingketv.com/xingketv/Test123456";
    }

    @Override
    protected void initViews(View view) {
        Log.i("sendmsg", "初始化");
        mcontext = this.getActivity();
        EventBus.getDefault().register(this);
        mThread = new HandlerThread("Work on RoomActivity");
        mThread.start();
        mBackgroundHandler = new BackgroundHandler(mThread.getLooper());

        userPublicMsg = new UserPublicMsg();
//        红包集合实例化
        hongbaolist = new ArrayList<SendGiftMsg>();
//        特殊礼物集合
        gitfSpecials=new ArrayList<>();
//        小星星
        starticon = new int[]{R.drawable.global_star_1, R.drawable.global_star_2, R.drawable.global_star_3, R.drawable.global_star_4, R.drawable.global_star_5};
        iconstart = (ImageView) view.findViewById(R.id.img_user_star_type);
        if (iconstart != null) {
            iconstart.setImageResource(starticon[(int) (Math.random() * 4)]);
        }
        if (getRoomType() == RoomActivity.TYPE_PUBLISH_LIVE) {
            publicMsgLevel = Integer.parseInt(LocalDataManager.getInstance().getLoginInfo().getLevel());
            publicMsgId = LocalDataManager.getInstance().getLoginInfo().getUserId();
            publicMsgName = LocalDataManager.getInstance().getLoginInfo().getNickname();
        }
        timingLogger.reset(TIMING_LOG_TAG, "RoomFragment#initViews");
        parseArguments(getArguments());
        timingLogger.addSplit("parseArguments");

        heartColorArray = getResources().getIntArray(R.array.room_heart_colors);
//        heartColorArray = new int[colorRefs.length];
//        for (int i=0; i<colorRefs.length; i++){
//            heartColorArray[i] = ContextCompat.getColor(getActivity(), colorRefs[i]);
//        }
        L.v(false, LOG_TAG, "Heart colors:%s", Arrays.toString(heartColorArray));
        defaultColorIndex = (int) (Math.random() * heartColorArray.length);
        L.d(LOG_TAG, "Default color for this room : %s", defaultColorIndex);
        timingLogger.addSplit("init heart color.");
        mRoomId = getWsRoomId();

        mPrvChat = $(view, R.id.dialog_user_info_prv_chat);
        llChatBar = $(view, R.id.room_ll_chat_bar);
        llOperationBar = $(view, R.id.room_ll_operation_bar);
        rlPrvChat = $(view, R.id.layout_prv_chat);
        rlPrvChat.setVisibility(View.GONE);
        mHeartAnim = $(view, R.id.room_heart_view);
        llHeader = $(view, R.id.room_header);
        mRankLay = $(view, R.id.room_coin_rank_lay);
        mRoot = $(view, R.id.room_fragment_root);
        mRoomScroll = $(view, R.id.room_scroll);
        tvGold = $(view, R.id.txt_gold_count);
        mWaterId = $(view, R.id.water_room_uid);
        mWaterId.setText("ID号: " + mAnchorId);
        mWaterDate = $(view, R.id.water_room_date);
        mWaterDate.setText(refFormatNowDate(System.currentTimeMillis()));
        ibBack = $(view, R.id.chat_back);
        ibToBack = $(view, R.id.chat_toback);
        llIn = $(view, R.id.input);
        llSys = $(view, R.id.room_chat);
        llSys.setVisibility(View.GONE);
        ibSysBack = $(view, R.id.chat_sysback);
        toptabstart = $(view, R.id.room_top_bar_start_tv);
        roomShow = $(view, R.id.room_chat_show);
        unRead = $(view, R.id.unread);
        newMsg = $(view, R.id.some_msg);

        mChatListView = $(view, R.id.room_chatlist);
        mChatInputEt = $(view, R.id.room_input);
        mSendMsgBtn = $(view, R.id.room_chat_send);
        mChatTitle = $(view, R.id.tv_chat_roomName);

        mChatInputEt.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        mChatInputEt.setSingleLine(false);
        mChatInputEt.setMaxLines(4);

        mMyName = "meilibo"+LocalDataManager.getInstance().getLoginInfo().getUserId();
        mMyPassword = "meilibo"+LocalDataManager.getInstance().getLoginInfo().getUserId();
        if (JMessageClient.getMyInfo() == null) {

            for (int i = 0; i < 5; i++) {
                L.e("lw", "注册操作" + i);
                register();
                if (r = true) {
                    break;
                }
            }
            if (r=true){
                for (int j = 0; j < 5; j++) {
                    L.e("lw", "登录操作"+j);
                    login();
                    if (f=true) {
                        break;
                    }
                }
            }
        }

        mFriendClose = $(view, R.id.layout_friend_btn_close);
        mFriendClose.setEnabled(true);
        try{
            mDatas = JMessageClient.getConversationList();
            L.e("lw","收到消息"+mDatas);
            for (int i=0;i<mDatas.size();i++){
                Conversation conv=mDatas.get(i);
                if (conv.getUnReadMsgCnt()>0) {
                    newMsg.setVisibility(View.VISIBLE);
                    break;
                }else
                    newMsg.setVisibility(View.GONE);
            }
        }catch (NullPointerException e){
        }

        this.mWindow = getActivity().getWindow();
        this.mImm = (InputMethodManager) mcontext.getSystemService(Context.INPUT_METHOD_SERVICE);


        moveLayout=$(view,R.id.room_move_layout);
//        ibBack.setFocusable(true);
//        ibBack.requestFocus();
        ibBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    mConv.resetUnreadCount();
                    dismissSoftInput();
                    JMessageClient.exitConversation();
//                    //发送保存为草稿事件到会话列表
                    if (mIsSingle) {
                        EventBus.getDefault().post(new Event.DraftEvent(mTargetId, mTargetAppKey,
                                mChatInputEt.getText().toString()));
                    }
                }catch (Exception e){
                }
                View view = getActivity().getWindow().peekDecorView();
                if (view != null) {
                    InputMethodManager inputmanger = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }

                showAnimOut(rlPrvChat);
                rlPrvChat.setVisibility(View.GONE);
//                llOperationBar.setVisibility(View.VISIBLE);
//                recyclerPublicChat.setVisibility(View.VISIBLE);
                showAnimIn(llSys);
                llSys.setVisibility(View.VISIBLE);
            }
        });
        ibToBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    mConv.resetUnreadCount();
                    dismissSoftInput();
                    JMessageClient.exitConversation();
//                    //发送保存为草稿事件到会话列表
                    if (mIsSingle) {
                        EventBus.getDefault().post(new Event.DraftEvent(mTargetId, mTargetAppKey,
                                mChatInputEt.getText().toString()));
                    }
                }catch (Exception e){
                }
                View view = getActivity().getWindow().peekDecorView();
                if (view != null) {
                    InputMethodManager inputmanger = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }

                showAnimOut(rlPrvChat);
                rlPrvChat.setVisibility(View.GONE);
//                llOperationBar.setVisibility(View.VISIBLE);
//                recyclerPublicChat.setVisibility(View.VISIBLE);
                showAnimIn(llSys);
                llSys.setVisibility(View.VISIBLE);
            }
        });
        ibSysBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAnimOut(llSys);
                llSys.setVisibility(View.GONE);
                llOperationBar.setVisibility(View.VISIBLE);
                recyclerPublicChat.setVisibility(View.VISIBLE);

                try{
                    mDatas = JMessageClient.getConversationList();
                    initDatas(mDatas);
                    L.e("lw","收到消息"+mDatas);

                    for (int i=0;i<mDatas.size();i++){
                        Conversation conv=mDatas.get(i);
                        if (conv.getUnReadMsgCnt()>0) {
                            newMsg.setVisibility(View.VISIBLE);
                            break;
                        }else
                            newMsg.setVisibility(View.GONE);
                    }
                }catch (NullPointerException e){
                }
            }
        });

        if (mHeartAnim != null && mRoot != null && mRoomScroll != null) {
            RxView.clicks(mRoomScroll)
                    .throttleFirst(Const.LIVE_ROOM_HEART_THROTTLE, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            onRootClickAction();
                        }
                    });
        }

        if (llChatBar != null) {
            edtChatContent = $(view, R.id.room_edt_chat);
            Button btnSendChat = $(view, R.id.room_btn_send);

            RxView.clicks(btnSendChat).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit
                    .MILLISECONDS)
                    .filter(new Func1<Void, Boolean>() {
                        @Override
                        public Boolean call(Void aVoid) {
                            userPublicMsg = new UserPublicMsg();
                            userPublicMsg.setLevel(publicMsgLevel);
                            userPublicMsg.setUserId(publicMsgId);
                            userPublicMsg.setFromClientName(publicMsgName);
                            userPublicMsg.setContent(edtChatContent.getText().toString());
//                            publicChatAdapter.appendData(userPublicMsg);
                            //Auto scroll to last
                            recyclerPublicChat.scrollToPosition(publicChatAdapter.getItemCount() - 1);
                            return !TextUtils.isEmpty(edtChatContent.getText().toString());
                        }
                    })
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            String msg = edtChatContent.getText().toString();
                            if (danmuopenis) {
                                senDanmu(LocalDataManager.getInstance().getLoginInfo().getToken(), mRoomId, msg);
                            } else {
                                wsService.sendRequest(WsObjectPool.newPublicMsgRequest(msg));
                            }
                            edtChatContent.setText("");
                        }
                    });
        }
        danmu_layout_close = $(view, R.id.room_danmu_close);
        danmu_layot_open = $(view, R.id.room_danmu_open);
        RxView.clicks($(view, R.id.room_danmu))
                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (danmuopenis) {
                            danmu_layout_close.setVisibility(View.VISIBLE);
                            danmu_layot_open.setVisibility(View.INVISIBLE);
                            danmuopenis = false;
                        } else {
                            danmu_layot_open.setVisibility(View.VISIBLE);
                            danmu_layout_close.setVisibility(View.INVISIBLE);
                            danmuopenis = true;
                        }
                    }
                });
        ImageButton imgbtn = $(view, R.id.room_imgbtn_public_chat);
        if (imgbtn != null) {
            RxView.clicks(imgbtn).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            showInputLayout(true);
                        }
                    });
        }

        LinearLayout giftLayout = $(view, R.id.room_ll_gift_bar);
        if (giftLayout != null) {
            List<IGiftAnimPlayer> playerViews = new ArrayList<>();
            int childCount = giftLayout.getChildCount();
            for (int i = 0; i < childCount; i++) {
                IGiftAnimPlayer player = (IGiftAnimPlayer) giftLayout.getChildAt(i);
                playerViews.add(player);
            }
            localGiftController = new LocalAnimQueue(playerViews);
        }



        recyclerPublicChat = $(view, R.id.room_recycler_chat);
        if (recyclerPublicChat != null) {
            recyclerPublicChat.setLayoutManager(new LinearLayoutManager(getActivity()));
            publicChatAdapter = new PublicChatAdapter(new ArrayList<RoomPublicMsg>());
            recyclerPublicChat.setAdapter(publicChatAdapter);
        }

        animLayout=$(view,R.id.room_live_show_anim_layout);
        friendLayout=$(view,R.id.layout_friend);
        friendLayout.setVisibility(View.GONE);
        ImageButton imgbtnfriend = $(view, R.id.room_imgbtn_friend);
        if (imgbtnfriend!=null) {
            RxView.clicks(imgbtnfriend)
                    .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            llOperationBar.setVisibility(View.GONE);
//                        showAnimOut(llOperationBar);
                            friendLayout.setVisibility(View.VISIBLE);
                            showAnimIn(friendLayout);
                            recyclerPublicChat.setVisibility(View.GONE);
                        }
                    });
        }

        mFriendClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("mrl","点击了");
                friendLayout.setVisibility(View.GONE);
                llOperationBar.setVisibility(View.VISIBLE);
                recyclerPublicChat.setVisibility(View.VISIBLE);
            }
        });


        initAudienceBar(view);
        subscribeCloseBtn(view);
        subscribeShowBtn(view);
        initReceiver();
        initreceiver();

        timingLogger.addSplit("init view & set listener");

        //TODO 添加网络连接状况检测
        initWebSocket();

        timingLogger.addSplit("initWebSocket");
        L.d(LOG_TAG, "Timing log is enabled?%s", Log.isLoggable(TIMING_LOG_TAG, Log.VERBOSE));
        timingLogger.dumpToLog();

        initDanmuku(view);
//        设置按钮
        if (mHeartAnim != null && mRoot != null && mRoomScroll != null && mDanmakuView != null) {
            RxView.clicks((View) mDanmakuView)
                    .throttleFirst(Const.LIVE_ROOM_HEART_THROTTLE, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            onRootClickAction();
                        }
                    });
        }

//      设置红包头像的size
        size = (int) getActivity().getResources().getDimension(R.dimen.item_gift_icon_size);

        try {

            mDatas = JMessageClient.getConversationList();
            if (mDatas != null && mDatas.size() > 1) {
                SortConvList sortList = new SortConvList();
                Collections.sort(mDatas, sortList);
//                mListAdapter.notifyDataSetChanged();
            }
            initDatas(mDatas);
            L.e("lw","我的消息数据"+mDatas);
            mListAdapter = new PrvListAdapter(mcontext, mDatas);
            roomShow.setAdapter(mListAdapter);
            if (mListAdapter != null) {
                mListAdapter.sortConvList();
            }

            unRead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListAdapter.resetConversation();
                }
            });
        }catch (NullPointerException e){
        }

        roomShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position > -1) {
                    Log.i("mrl",mListAdapter.getmDatas().size()+"changdu");
                    Conversation conv = mListAdapter.getmDatas().get(position);
                    if (null != conv) {
                        mTargetId = ((cn.jpush.im.android.api.model.UserInfo) conv.getTargetInfo()).getUserName();
                        mTargetAppKey = conv.getTargetAppKey();
                        draft = mListAdapter.getDraft(conv.getId());
                        showAnimIn(rlPrvChat);
                        llOperationBar.setVisibility(View.GONE);
                        recyclerPublicChat.setVisibility(View.GONE);
                        llSys.setVisibility(View.GONE);
                        rlPrvChat.setVisibility(View.VISIBLE);
                        try{
                        mMyInfo = JMessageClient.getMyInfo();
                        if (!TextUtils.isEmpty(mTargetId)) {
                            mIsSingle = true;
                            mConv = JMessageClient.getSingleConversation(mTargetId, mTargetAppKey);
                            if (mConv != null) {
                                cn.jpush.im.android.api.model.UserInfo userInfo = (cn.jpush.im.android.api.model.UserInfo) mConv.getTargetInfo();
                                if (TextUtils.isEmpty(userInfo.getNickname())) {
                                    mChatTitle.setText(userInfo.getUserName());
                                } else {
                                    mChatTitle.setText(userInfo.getNickname());
                                }
                            } else {
                                mConv = Conversation.createSingleConversation(mTargetId, mTargetAppKey);
                                cn.jpush.im.android.api.model.UserInfo userInfo = (cn.jpush.im.android.api.model.UserInfo) mConv.getTargetInfo();
                                if (TextUtils.isEmpty(userInfo.getNickname())) {
                                    mChatTitle.setText(userInfo.getUserName());
                                } else {
                                    mChatTitle.setText(userInfo.getNickname());
                                }
                            }
                            mChatAdapter = new MsgListRoomAdapter(mcontext, mTargetId, mTargetAppKey, longClickListener);
                        }
                        if (draft != null && !TextUtils.isEmpty(draft)) {
                            mChatInputEt.setText(draft);
                        }
                        mChatListView.setAdapter(mChatAdapter);

                        mChatAdapter.initMediaPlayer();
                        // 监听下拉刷新
                        mChatListView.setOnDropDownListener(new DropDownListView.OnDropDownListener() {
                            @Override
                            public void onDropDown() {
                                mUIHandler.sendEmptyMessageDelayed(REFRESH_LAST_PAGE, 1000);
                            }
                        });
                        // 滑动到底部
                        mChatListView.clearFocus();
                            mChatListView.post(new Runnable() {
                            @Override
                            public void run() {
                                mChatListView.setSelection(mChatListView.getAdapter().getCount() - 1);
                                mChatListView.smoothScrollToPosition(mChatListView.getAdapter().getCount() - 1);
                                L.e("lw","滑到底"+(mChatListView.getAdapter().getCount() - 1));
                            }
                        });
                        }catch (NullPointerException e){
                        }

                        mSendMsgBtn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ibBack.setFocusable(true);
                                ibBack.requestFocus();
                                String msgContent = mChatInputEt.getText().toString();
                                mChatInputEt.setText("");

                                mChatListView.clearFocus();
                                mChatListView.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mChatListView.setSelection(mChatListView.getAdapter().getCount() - 1);
                                    }
                                });

                                if (msgContent.equals("")) {
                                    return;
                                }
                                TextContent content = new TextContent(msgContent);
                                cn.jpush.im.android.api.model.Message msg = mConv.createSendMessage(content);
                                mChatAdapter.addMsgToList(msg);
                                JMessageClient.sendMessage(msg);

                            }
                        });
                    }

                }
            }
        });

        roomShow.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                if (position >= 0) {
                    final Conversation conv = mDatas.get(position);
                    if (conv != null) {
                        View.OnClickListener listener = new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (conv.getType() == ConversationType.group) {
                                    JMessageClient.deleteGroupConversation(((GroupInfo) conv.getTargetInfo())
                                            .getGroupID());
                                } else {
                                    //使用带AppKey的接口,可以删除跨/非跨应用的会话(如果不是跨应用,conv拿到的AppKey则是默认的)
                                    JMessageClient.deleteSingleConversation(((cn.jpush.im.android.api.model.UserInfo) conv.getTargetInfo())
                                            .getUserName(), conv.getTargetAppKey());
                                }
                                conv.resetUnreadCount();
                                mListAdapter.removeSl(position);
                                mDialog.dismiss();
                            }
                        };
                        mDialog = DialogCreator.createDelConversationDialog(mcontext, conv.getTitle(),
                                listener);
                        mDialog.show();
                        mDialog.getWindow().setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT);
                    }
                }
                return true;
            }
        });
    }

    protected void onRootClickAction() {
        mHeartAnim.addLove(heartColorArray[defaultColorIndex]);
        friendLayout.setVisibility(View.GONE);
        boolean shouldSend = shouldSendHeartRequest();
//        L.d(LOG_TAG, "shouldSendHeartRequest=%s, defaultColorIndex=%d", shouldSend, defaultColorIndex);
        if (shouldSend) {
            wsService.sendRequest(WsObjectPool.newLightHeartRequest(defaultColorIndex));
        }
    }

    @Override
    public void onDestroyView() {
        timingLogger.reset(TIMING_LOG_TAG, "RoomFragment#onDestroyView");
        super.onDestroyView();
        timingLogger.addSplit("super.onDestroyView");

        //清除动画
        if (localGiftController != null) {
            localGiftController.removeAll();
        }
        if (wsConnection != null) {
            getActivity().unbindService(wsConnection);
        }
        //Release ws service binding
        if (wsService == null) {
            L.e(LOG_TAG, "Ws service reference has been null, logout action cannot perform!");
            return;
        }
//        2016年8月2日17:47:54 鹏哥说的 发送两次logout不会出事
        if (!isKicked) {
            wsService.sendRequest(WsObjectPool.newLogoutRequest(mRoomId));
        }
        wsService.removeAllListeners();
        timingLogger.addSplit("reset webSocket");
        timingLogger.dumpToLog();
    }

//    初始化webSocket
    private void initWebSocket() {
        getActivity().bindService(WebSocketService.createIntent(getActivity()),
                wsConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 因为WebSocket能连接的时间具有不确定性，所以必须在ServiceConnection里初始化。
     */
    protected void initWsListeners() {
        WsListener<WsLoginMsg> loginListener = new WsListener<WsLoginMsg>() {

            @Override
            public void handleData(WsLoginMsg wsLoginMsg) {
                isRoomAdmin = !TextUtils.isEmpty(wsLoginMsg.getRole());
            }
        };
        wsService.registerListener(SocketConstants.EVENT_LOGIN, loginListener);
//
        WsListener<WsLoginOutMsg> loginOutMsgWsListener = new WsListener<WsLoginOutMsg>() {
            @Override
            public void handleData(WsLoginOutMsg wsLoginOutMsg) {
                if (wsLoginOutMsg.getUser_id() != null && mAnchorId.equals(wsLoginOutMsg.getUser_id())) {
                    isloginout = true;
                    ((RoomActivity) getActivity()).showRoomEndInfoDialog();
                }
            }
        };
        wsService.registerListener(SocketConstants.EVENT_LOGOUT, loginOutMsgWsListener);

        final WsListener<ErrorMsg> errorListener = new WsListener<ErrorMsg>() {
            private AlertDialog alertDialog;
            @Override
            public void handleData(ErrorMsg errorMsg) {
                if (SocketConstants.ERROR_KICKED.equalsIgnoreCase(errorMsg.getType())) {
                    if (alertDialog == null) {
                        final BaseActivity activity = (BaseActivity) getActivity();
                        String sysmsg = TextUtils.isEmpty(errorMsg.getContent())
                                ? "你被管理员请出房间"
                                : errorMsg.getContent();
                        sysmsg = sysmsg + "，五秒后自动退出";
                        new Thread(new ThreadShow()).start();
                        alertDialog = new AlertDialog.Builder(activity)
                                .setCancelable(false)
                                .setMessage(sysmsg)
                                .setPositiveButton("立即退出", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
//                                        是否被踢出 设为true
                                        isKicked = true;
                                        FINISH_ROOM = true;
//                                        activity.startActivity(LoginSelectActivity.createIntent(activity));
//                                        activity.sendFinishBroadcast(LoginSelectActivity.class.getSimpleName());
                                        ((RoomActivity) getActivity()).finishRoomActivity();
                                    }
                                })
                                .create();
                        alertDialog.show();
                    }
                } else {
                    String msg = TextUtils.isEmpty(errorMsg.getContent()) ? errorMsg.getType()
                            : errorMsg.getContent();
                    toastShort(msg);
                    L.e(LOG_TAG, "Unsupported error type:%s", errorMsg.getType());
                }
            }
        };
        wsService.registerListener(SocketConstants.EVENT_ERROR, errorListener);

//        接受用户发出的消息
        WsListener<UserPublicMsg> chatListener = new WsListener<UserPublicMsg>() {
            @Override
            public void handleData(UserPublicMsg msg) {
//                Log.i("sendmsg","这个是handlerdata"+msg.getUserId()+"   "+userPublicMsg.getUserId());
//                addDanmaKuShowTextAndImage(false,msg.getContent());
//                Bitmap bitmap=Glide.with(RoomFragment.this).load("http://www.bilibili.com/favicon.ico").diskCacheStrategy(DiskCacheStrategy.ALL);

//                request = NoHttp.createImageRequest("http://www.bilibili.com/favicon.ico");
//                if (request != null)
//                    CallServer.getRequestInstance().add(getActivity(), 0, request, RoomFragment.this, false, true);
                if (msg.getFly() != null && msg.getFly().equals("FlyMsg")) {
                    danmu = new Danmu(0, (int) (Math.random() * (3)), "Comment", msg.getFromClientName() + ": " + msg.getContent());
                    Glide.with(RoomFragment.this).load(Const.MAIN_HOST_URL + msg.getAvatar()).asBitmap().into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            danmu.setAvatarUrl(resource);
                            mDanmuControl.addDanmu(danmu, 1);
                        }
                    });
                }
//                如果不是用户本人的信息则添加到Recycleview
//                if (!msg.getUserId().equals(userPublicMsg.getUserId())) {
                publicChatAdapter.appendData(msg);
                //Auto scroll to last
                recyclerPublicChat.scrollToPosition(publicChatAdapter.getItemCount() - 1);
//                }

            }
        };
        wsService.registerListener(SocketConstants.EVENT_PUB_MSG, chatListener);

//        接受系统发出的警告
        WsListener<SystemMsg> msgListenet = new WsListener<SystemMsg>() {
            @Override
            public void handleData(SystemMsg systemMsg) {
                publicChatAdapter.appendData(systemMsg);
                //Auto scroll to last
                recyclerPublicChat.scrollToPosition(publicChatAdapter.getItemCount() - 1);
            }
        };
        wsService.registerListener(SocketConstants.STSTEM_MSG, msgListenet);

        //        接受系统发出的欢迎
        WsListener<SystemWelcome> welcomeListenet = new WsListener<SystemWelcome>() {
            @Override
            public void handleData(SystemWelcome systemMsg) {
                publicChatAdapter.appendData(systemMsg);
                //Auto scroll to last
                recyclerPublicChat.scrollToPosition(publicChatAdapter.getItemCount() - 1);
            }
        };
        wsService.registerListener(SocketConstants.EVENT_LOGIN, welcomeListenet);


        WsListener<LightHeartMsg> heartListener = new WsListener<LightHeartMsg>() {
            @Override
            public void handleData(LightHeartMsg lightHeartMsg) {
                //要插入一条聊天数据
                publicChatAdapter.appendData(lightHeartMsg);
                //Auto scroll to last
                recyclerPublicChat.scrollToPosition(publicChatAdapter.getItemCount() - 1);
                //画心，如果不是来自自己的点亮
                String myUserId = LocalDataManager.getInstance().getLoginInfo().getUserId();
                if ((!TextUtils.isEmpty(myUserId)) && (!myUserId.equalsIgnoreCase(lightHeartMsg
                        .getFromUserId()))) {
                    int colorIndex = lightHeartMsg.getColor();
                    //设置安全的默认值
                    if (colorIndex < 0 || colorIndex >= heartColorArray.length) {
                        colorIndex = 0;
                    }
                    mHeartAnim.addLove(heartColorArray[colorIndex]);
                }
            }
        };
        wsService.registerListener(SocketConstants.EVENT_LIGHT_HEART, heartListener);


        if (localGiftController != null) {
            WsListener<SendGiftMsg> giftAnimListener = new WsListener<SendGiftMsg>() {
                @Override
                public void handleData(SendGiftMsg sendGiftMsg) {
                    try {
                        int giftis=Integer.parseInt(sendGiftMsg.getIsred());
                        int giftCount=sendGiftMsg.getGiftCount();
                        if (giftis>1) {
                            for (int i=0;i<giftCount;i++) {
                                gitfSpecials.add(giftis);
                            }
                            if (isgiftend==true) {
                                isgiftend=false;
                                showAnim(gitfSpecials.get(0));
                            }
                        }
                        Log.i("mrl",sendGiftMsg.getIsred()+"礼物的"+sendGiftMsg.getGiftCount());
                    }catch (NumberFormatException e){
                        toastShort("服务器开小差咯");
                    }
//                    判断是否是红包
                    if (sendGiftMsg.getIsred().equals("1")) {
                        hongbaolist.add(sendGiftMsg);
                        if (mPopupWindow != null && !mPopupWindow.isShowing()) {
                            statusPopupWindow(hongbaolist.get(0).getRed_Id(), hongbaolist.get(0).getFromUserName(), hongbaolist.get(0).getFromUserAvatar());
                        } else if (mPopupWindow == null) {
                            statusPopupWindow(hongbaolist.get(0).getRed_Id(), hongbaolist.get(0).getFromUserName(), hongbaolist.get(0).getFromUserAvatar());
                        }
                    }
                    for (int i = 0; i < sendGiftMsg.getGiftCount(); i++) {
                        publicChatAdapter.appendData(sendGiftMsg);
                    }
                    //Auto scroll to last
                    if (!sendGiftMsg.getIsred().equals("1")) {
                        tvGold.setText(String.valueOf(sendGiftMsg.getAnchorBalance()));
                    }
                    recyclerPublicChat.scrollToPosition(publicChatAdapter.getItemCount() - 1);
                    localGiftController.enqueue(adapter(sendGiftMsg));
                }

                private SendGiftAction adapter(SendGiftMsg msg) {
                    SendGiftAction action = new SendGiftAction();
                    action.setAvatar(msg.getFromUserAvatar());
                    action.setFromUid(msg.getFromUserId());
                    action.setCombo(msg.getGiftCount());
                    action.setNickname(msg.getFromUserName());
                    action.setGiftIcon(msg.getGiftIcon());
                    action.setGiftName(msg.getGiftName());
                    return action;
                }
            };
            wsService.registerListener(SocketConstants.EVENT_SEND_GIFT, giftAnimListener);
        }

        if (recyclerAudienceList != null) {
            WsListener<LiveAudienceListMsg> liveListener = new WsListener<LiveAudienceListMsg>() {
                @Override
                public void handleData(LiveAudienceListMsg msg) {
                    if (recyclerAudienceList != null && audienceAdapter != null) {
                        List<AudienceInfo> total = new ArrayList<>();
                        List<AudienceInfo> clients = msg.getClientList();
                        List<AudienceInfo> admins = msg.getAdminList();
                        total.addAll(admins);
                        //Collections.copy cause lots of bugs.
                        total.addAll(clients);
                        L.v(false, LOG_TAG, "clients=%d, admin=%d, total=%d", clients.size(),
                                admins.size
                                        (), total.size());
//                        audienceAdapter.setDataList(total);
                        screenAudienList(audienceAdapter.getDataList(), total, audienceAdapter);
                    }
                    tvOnlineCount.setText(String.valueOf(msg.getTotalCount()));
                }
            };
            wsService.registerListener(SocketConstants.EVENT_ONLINE_CLIENT, liveListener);
        }
//        聊天的msg的点击事件
        publicChatAdapter.setOnItemClickListener(new PublicChatAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, RoomPublicMsg data) {
                UserPublicMsg msg;
                try {
                    msg = (UserPublicMsg) data;
                } catch (Exception e) {
                    Log.i("mrl", e + "错误");
                    return;
                }
                if (msg.getUserId() != null && !msg.getUserId().equals(userPublicMsg.getUserId())) {
                    UserInfo mInfo = new UserInfo();
                    mInfo.setId(msg.getUserId());
                    mInfo.setAvatar("");
                    mInfo.setNickname(msg.getFromClientName());
                    mInfo.setVip(msg.getVipLevel() + " ");
                    mInfo.setLevel(msg.getLevel() + "");
                    mInfo.setCurrentRoomNum("");
                    showUserInfoDialog(mInfo);
                }
            }
        });
    }

    private void subscribeCloseBtn(View view) {
        RxView.clicks($(view, R.id.room_imgbtn_close))
                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        //观众点击叉叉时不需要提示
                        ((RoomActivity) getActivity()).exitLiveRoom(getRoomType() != RoomActivity.TYPE_VIEW_LIVE);
                    }
                });
    }

    private void subscribeShowBtn(View view) {
        RxView.clicks($(view, R.id.room_imgbtn_prvchat))
                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        llOperationBar.setVisibility(View.GONE);
                        recyclerPublicChat.setVisibility(View.GONE);
                        llSys.setVisibility(View.VISIBLE);
                        showAnimIn(llSys);
                    }
                });
    }

    private void initReceiver() {
        mReceiver = new NetworkReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        mcontext.registerReceiver(mReceiver, filter);
    }

    //监听网络状态的广播
    private class NetworkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
                ConnectivityManager manager = (ConnectivityManager) mcontext.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeInfo = manager.getActiveNetworkInfo();
                if (null == activeInfo) {
                    L.e("lw","网络状况差");
                }
            }
        }

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

    }

    private void initAudienceBar(View view) {
        tvOnlineCount = $(view, R.id.room_tv_live_user_count);

        TextView tvUserCountType = $(view, R.id.room_tv_label_user_count);
        recyclerAudienceList = $(view, R.id.room_recycler_audience);
        recyclerAudienceList.setLayoutManager(new LinearLayoutManager(getActivity(),
                LinearLayoutManager.HORIZONTAL, false));
        recyclerAudienceList.addItemDecoration(ItemDecorations.horizontal(getActivity())
                .type(0, R.drawable.divider_decoration_transparent_w5)
                .create());

        audienceAdapter = new AudienceAdapter(new ArrayList<AudienceInfo>());
        recyclerAudienceList.setAdapter(audienceAdapter);
        switch (getRoomType()) {
            case RoomActivity.TYPE_VIEW_LIVE://fall down
            case RoomActivity.TYPE_PUBLISH_LIVE:
                tvUserCountType.setText(R.string.room_label_live_user_count);
                break;
            case RoomActivity.TYPE_VIEW_REPLAY:
                tvUserCountType.setText(R.string.room_label_replay_user_count);
                break;
        }
    }

    /**
     * 返回子类的房间类型，用于直接处理一些简单公用的属性。
     */
    @RoomActivity.RoomType
    protected abstract int getRoomType();

    /**
     * 解析参数。
     * 该方法会在initView之前调用。
     */
    protected abstract void parseArguments(Bundle bundle);

    /**
     * WebSocket聊天房间号。
     */
    protected abstract String getWsRoomId();

    protected abstract boolean shouldSendHeartRequest();

    @Override
    public void showInputLayout(boolean show) {
        L.v(false, LOG_TAG, "showInputLayout:%s", show);
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        if (show) {
            llChatBar.setVisibility(View.VISIBLE);
//            llHeader.setVisibility(View.GONE);
//            new Handler().postDelayed(new Runnable(){
//
//                @Override
//                public void run() {
            llHeader.setVisibility(View.INVISIBLE);
            Animation headerAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.top_out);
            llHeader.startAnimation(headerAnim);
//                }
//
//            }, 100);


            edtChatContent.requestFocus();
            imm.showSoftInput(edtChatContent, InputMethodManager.SHOW_IMPLICIT);

            llOperationBar.setVisibility(View.INVISIBLE);
        } else {

            llOperationBar.setVisibility(View.VISIBLE);
            /**
             * 使用handler来处理
             */
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    llHeader.setVisibility(View.VISIBLE);
                    Animation headerAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.top_in);
                    llHeader.startAnimation(headerAnim);
                }

            }, 50);

            llChatBar.setVisibility(View.INVISIBLE);

            imm.hideSoftInputFromWindow(edtChatContent.getWindowToken(), InputMethodManager
                    .HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public ViewGroup getInputLayout() {
        return llChatBar;
    }

    @Override
    public RelativeLayout getFriendLayout() {
        return friendLayout;
    }
//     隐藏
    @Override
    public void hideFriendLayout() {
        llOperationBar.setVisibility(View.VISIBLE);
        friendLayout.setVisibility(View.GONE);
        recyclerPublicChat.setVisibility(View.VISIBLE);
    }

    /**
     * 辅助方法， 用于将PopupWindow显示在图标上方。
     */
    protected final void showPopupWindowAboveButton(@NonNull PopupWindow window, @NonNull View
            anchor) {
        View popupView = window.getContentView();
        //执行一次measure，避免第一次无法获取位置的问题。
        popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = popupView.getMeasuredWidth();
        int popupHeight = popupView.getMeasuredHeight();
        int[] location = new int[2];
        anchor.getLocationOnScreen(location);
        //To fix the bug of inability for automatically dismiss pop window when touch outside
        window.setBackgroundDrawable(new BitmapDrawable());
        window.setOutsideTouchable(true);
        window.showAtLocation(anchor, Gravity.NO_GRAVITY, (location[0] + anchor.getWidth() / 2)
                        - popupWidth / 2,
                location[1] - popupHeight);
    }

    UserInfoDialog dialog;
    boolean m=false;

    /**
     * 展示用户信息的弹出框
     */
    protected void showUserInfoDialog(@NonNull final UserInfo info) {
        if (info == null) {
            toastShort("用户信息错误");
            return;
        }
        if (TextUtils.isEmpty(info.getId())) {
            toastShort("错误的用户ID");
            return;
        }
        L.e("lww", "UI"+info);
//        dialog=new UserInfoDialog(this.getActivity(), wsService, mAnchorId);
        dialog = new UserInfoDialog(this.getActivity(), wsService, mAnchorId, mRoomId, new UserInfoDialog.ChatListener() {
            @Override
            public void prvChatListener() {
                L.e("更新", "UI");
//                draft= mListAdapter.getDraft(conv.getId());
                mTargetId = info.getId();
                L.e("lw", "UI"+info.getId());
            if(!info.getId().isEmpty()){
                String id="meilibo"+info.getId();
                mTargetId=id;
                for (int i = 0; i < 5; i++) {
                    L.e("lw", "注册操作" + i);
                    JMessageClient.register(id, id, new BasicCallback() {
                        @Override
                        public void gotResult(int status, String desc) {
                            if (status == 0) {
                                L.e("lw","注册成功");
                                m=true;
                            } else {
                                L.e("lw", "注册失败" + status + desc);
                                if (desc.equals("user exist")) {
                                    m=true;
                                }
                            }
                        }
                    });
                    if (m = true) {
                        break;
                    }
                }
            }
                L.e("lw", "UI"+mTargetId);
                showAnimIn(rlPrvChat);
                llOperationBar.setVisibility(View.GONE);
                recyclerPublicChat.setVisibility(View.GONE);
                llSys.setVisibility(View.GONE);
                rlPrvChat.setVisibility(View.VISIBLE);

                try{
                mMyInfo = JMessageClient.getMyInfo();
                if (!TextUtils.isEmpty(mTargetId)) {
                    mIsSingle = true;
                    mConv = JMessageClient.getSingleConversation(mTargetId);
                    L.e("lw", "id+"+mTargetId);
                    if (mConv != null) {
                        cn.jpush.im.android.api.model.UserInfo userInfo = (cn.jpush.im.android.api.model.UserInfo) mConv.getTargetInfo();
                        L.e("lw","他的名字3+"+userInfo.getNickname()+"+"+userInfo.getUserName()+"+"+info.getNickname());
                        if (!TextUtils.isEmpty(info.getNickname())){
                            mChatTitle.setText(info.getNickname());
                        }else{
                            L.e("lw","他的名字3");
                            if (TextUtils.isEmpty(userInfo.getNickname())) {
                                mChatTitle.setText(userInfo.getUserName());
                            }else {
                                mChatTitle.setText(userInfo.getNickname());
                            }
                        }
                    } else {
                        mConv = Conversation.createSingleConversation(mTargetId);
                        final cn.jpush.im.android.api.model.UserInfo userInfo = (cn.jpush.im.android.api.model.UserInfo) mConv.getTargetInfo();
                        L.e("lw","他的名字4+"+userInfo+"+"+userInfo.getNickname()+"+"+userInfo.getUserName()+"+"+info.getNickname());
                        if (!TextUtils.isEmpty(info.getNickname())){
                            mChatTitle.setText(info.getNickname());
                        }else{
                            JMessageClient.getUserInfo(mTargetId, new GetUserInfoCallback() {
                                @Override
                                public void gotResult(int i, String s, cn.jpush.im.android.api.model.UserInfo userInfo) {
                                    cn.jpush.im.android.api.model.UserInfo serInfo=userInfo;
                                    mChatTitle.setText(serInfo.getNickname());
                                    L.e("lw","他的名字4+"+serInfo.getNickname());
                                }
                            });
//                            if (TextUtils.isEmpty(userInfo.getNickname())) {
//                                mChatTitle.setText(userInfo.getUserName());
//                            }else {
//                                mChatTitle.setText(userInfo.getNickname());
//                            }
                        }
                        mListAdapter.addNewConversation(mConv);
                    }
                    mChatAdapter = new MsgListRoomAdapter(mcontext, mTargetId, mTargetAppKey, longClickListener);
                }
                if (draft != null && !TextUtils.isEmpty(draft)) {
                    mChatInputEt.setText(draft);
                }
                mChatListView.setAdapter(mChatAdapter);
                // 滑动到底部
                mChatListView.clearFocus();
                mChatListView.post(new Runnable() {
                    @Override
                    public void run() {
                        mChatListView.setSelection(mChatListView.getAdapter().getCount() - 1);
                        mChatListView.smoothScrollToPosition(mChatListView.getAdapter().getCount() - 1);
                    }
                });
                    mChatListView.setSelection(mChatListView.getAdapter().getCount() - 1);
                }catch (NullPointerException e){
                }
                mSendMsgBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ibBack.setFocusable(true);
                        ibBack.requestFocus();
                        String msgContent = mChatInputEt.getText().toString();
                        mChatInputEt.setText("");

                        mChatListView.clearFocus();
                        mChatListView.post(new Runnable() {
                            @Override
                            public void run() {
                                mChatListView.setSelection(mChatListView.getAdapter().getCount() - 1);
                            }
                        });

                        if (msgContent.equals("")) {
                            return;
                        }
                        TextContent content = new TextContent(msgContent);
                        cn.jpush.im.android.api.model.Message msg = mConv.createSendMessage(content);
                        mChatAdapter.addMsgToList(msg);
                        JMessageClient.sendMessage(msg);

                        mChatAdapter.initMediaPlayer();
                        // 监听下拉刷新
                        mChatListView.setOnDropDownListener(new DropDownListView.OnDropDownListener() {
                            @Override
                            public void onDropDown() {
                                mUIHandler.sendEmptyMessageDelayed(REFRESH_LAST_PAGE, 1000);
                            }
                        });
                        // 滑动到底部
                        mChatListView.clearFocus();
                        mChatListView.post(new Runnable() {
                            @Override
                            public void run() {
                                mChatListView.setSelection(mChatListView.getAdapter().getCount() - 1);
                            }
                        });
                    }
                });
            }
        });
        dialog.setUserInofo(info);
        dialog.setUserId(info.getId());
        if ((getRoomType() == RoomActivity.TYPE_PUBLISH_LIVE)) {
            dialog.setKickListener(new UserInfoDialog.UserClickKickListener() {
                @Override
                public void clickKick(String userId, String username) {
                    wsService.sendRequest(WsObjectPool.newRoomManageRequest(WsRoomManageRequest.TYPE_KICK,
                            userId,
                            username));
                }
            });
            dialog.showKick(true);
        }
        Window win = dialog.getWindow();
        int margin = (int) this.getContext().getResources().getDimension(R.dimen.dialog_margin);
        win.getDecorView().setPadding(margin, margin, margin, margin);
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        win.setAttributes(lp);
        dialog.show();
    }

    public void setmAnchorId(String mAnchorId) {
        this.mAnchorId = mAnchorId;
    }

    private class AudienceAdapter extends SimpleRecyclerAdapter<AudienceInfo, AudienceHolder> {

        public AudienceAdapter(List<AudienceInfo> audienceInfoList) {
            super(audienceInfoList);
        }

        @Override
        protected int getItemLayoutId(int viewType) {
            return R.layout.item_online_audience;
        }

        @NonNull
        @Override
        protected AudienceHolder createHolder(View view) {
            return new AudienceHolder(view);
        }
    }

    private class AudienceHolder extends SimpleRecyclerHolder<AudienceInfo> {

        private SimpleDraweeView draweeAvatar;
        private ImageView icon;
        private UserInfo mInfo;

        public AudienceHolder(View itemView) {
            super(itemView);
            draweeAvatar = $(itemView, R.id.img_user_avatar);
            icon = $(itemView, R.id.img_user_star_type);
        }

        @Override
        public void displayData(final AudienceInfo data) {
//            判断当前用户是哪个观众，然后设置一下userPublicMsg的信息
            if (LocalDataManager.getInstance().getLoginInfo().getUserId().equals(data.getUserId()) && !initUserPublicMsg) {
                publicMsgLevel = Integer.parseInt(data.getLevelId());
                publicMsgId = data.getUserId();
                publicMsgName = data.getClientName();
                initUserPublicMsg = true;
            }
            String avatar = data.getAvatar();
            mInfo = new UserInfo();
            mInfo.setId(data.getUserId());
            mInfo.setAvatar(data.getAvatar());
            mInfo.setNickname(data.getClientName());
            mInfo.setVip(data.getVip() + "");
            mInfo.setLevel(data.getLevelId());
            mInfo.setCurrentRoomNum(data.getRoomId());
            if (!TextUtils.isEmpty(avatar)) {
                draweeAvatar.setImageURI(SourceFactory.wrapPathToUri(avatar));
            }
            L.e("lw","UI++"+data+data.getClientName());
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialog == null) {
                        showUserInfoDialog(mInfo);
                        L.e("lw","UI"+mInfo);
                    } else if (!dialog.isShowing()) {
                        showUserInfoDialog(mInfo);
                    }
                }
            });
            icon.setImageResource(starticon[(int) (Math.random() * 4)]);
        }
    }

    protected void showAnimIn(View v) {
        Animation headerAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.room_buttom_in);
        v.startAnimation(headerAnim);
    }

    protected void showAnimOut(View v) {
        Animation headerAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.room_buttom_out);
        v.startAnimation(headerAnim);
    }

    protected int getSurfaceViewHeight() {
        DisplayMetrics dm = new DisplayMetrics();
        //取得窗口属性
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);


        //因为部分（乐视）手机的系统栏高度不是标准的25/24dp，所以首选获得系统内置的高度，出现异常时则用预定义的高度。
        int statusBarHeight;
        try {
            statusBarHeight = getResources().getDimensionPixelSize(getResources().getIdentifier
                    ("status_bar_height", "dimen", "android"));
            L.i(LOG_TAG, "System status bar height:%s", statusBarHeight);
        } catch (Exception e) {
            L.w(LOG_TAG, "Cannot get system status bar height, using default!");
            statusBarHeight = (int) getResources().getDimension(R.dimen.status_bar_height);
        }
        //窗口的宽度
        return dm.heightPixels - statusBarHeight;
    }

    //    是否执行
    private boolean FINISH_ROOM = false;
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                ((RoomActivity) getActivity()).finishRoomActivity();
            }else if (msg.what==21){
                for (String value : mFuImgUrl.values()) {
                    Log.i("mrl",value+"地址？");
                }
                mListAdapter = new PrvListAdapter(mcontext, mDatas,mFuImgUrl);
                roomShow.setAdapter(mListAdapter);
            }
            super.handleMessage(msg);
        }

        ;
    };

    // d计时器
    class ThreadShow implements Runnable {
        @Override
        public void run() {
            int i = 0;
            while (i < 5 && !FINISH_ROOM) {
                try {
                    i++;
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                    toastShort("未知错误");
                }
            }
            if (!FINISH_ROOM) {
                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);
            }
        }
    }

    private DanmuControl mDanmuControl;

    private void initDanmuku(View view) {
        mDanmuControl = new DanmuControl(getActivity());
//        弹幕实力话
        mDanmakuView = (DanmakuView) view.findViewById(R.id.mrl_danmaku);
        mDanmuControl.setDanmakuView(mDanmakuView);
        mDanmakuView.setOnDanmakuClickListener(new IDanmakuView.OnDanmakuClickListener() {
            @Override
            public void onDanmakuClick(BaseDanmaku latest) {
                Log.i("mrl", latest + " ");
            }

            @Override
            public void onDanmakuClick(IDanmakus danmakus) {
                Log.i("mrl", danmakus + " ");
            }
        });

    }

    //    成功的请求
    @Override
    public void onSucceed(int what, Response<Bitmap> response) {
        danmu.setAvatarUrl(response.get());
        mDanmuControl.addDanmu(danmu, 1);
    }

    //  失败
    @Override
    public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {

    }

    View view;
    PopupWindow mPopupWindow;
    ImageView get;
    ImageView close;
    String giftid;
    SimpleDraweeView hbfromicon;
    TextView hbfromnikname, hongbaoamount;
    RelativeLayout hongbao;
    int size;

    //    红包弹窗                      红包id        发送的人名字  发送人的头像
    private void statusPopupWindow(String gifid, String nikname, String icon) {
        Log.i("mrl", Const.MAIN_HOST_URL + icon);
        giftid = gifid;
        if (mPopupWindow == null) {
            LayoutInflater relativeLayout = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = relativeLayout.inflate(R.layout.layout_hongbao_popu, null);
            hongbao = (RelativeLayout) view.findViewById(R.id.hongbao);
            get = (ImageView) view.findViewById(R.id.get);
            close = (ImageView) view.findViewById(R.id.close);
            hbfromnikname = (TextView) view.findViewById(R.id.hongbao_name);
            hongbaoamount = (TextView) view.findViewById(R.id.hongbao_amount);
            hbfromicon = (SimpleDraweeView) view.findViewById(R.id.hongbao_head);
            hbfromnikname.setText(nikname);
            hbfromicon.setImageURI(Uri.parse(Const.MAIN_HOST_URL + icon));
            get.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mRoomId != null) {
                        Log.i("mrl", LocalDataManager.getInstance().getLoginInfo().getToken() + " " + mRoomId + "  " + giftid);
                        getViewPagerJson(LocalDataManager.getInstance().getLoginInfo().getToken(), mRoomId, giftid);
                    }
                }
            });
            close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (hongbaolist.size() > 1) {
                        mPopupWindow.dismiss();
                        hongbaolist.remove(0);
                        statusPopupWindow(hongbaolist.get(0).getRed_Id(), hongbaolist.get(0).getFromUserName(), hongbaolist.get(0).getFromUserAvatar());
                    } else {
                        hongbaolist.remove(0);
                        mPopupWindow.dismiss();
                    }
                }
            });
            mPopupWindow = new PopupWindow(view,
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            // 使其聚集
            mPopupWindow.setFocusable(true);
            // 设置允许在外点击消失
            mPopupWindow.setOutsideTouchable(true);
            // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mPopupWindow.showAtLocation(tvGold, Gravity.BOTTOM, 0, 0);
            aniPopupWindowValuesHolder(hongbao);
            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        } else {
            hbfromnikname.setText(nikname);
            get.setVisibility(View.VISIBLE);
            hongbaoamount.setText("给你发来了一个红包");
            hbfromicon.setImageURI(Uri.parse(Const.MAIN_HOST_URL + icon));
            mPopupWindow.showAtLocation(tvGold, Gravity.BOTTOM, 0, 0);
            aniPopupWindowValuesHolder(hongbao);
        }
    }


    int PAGER_JSON = 1;

    //Mrl L
    public void getViewPagerJson(String token, String roomuid, String gifid) {
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(Const.MAIN_HOST_URL + "/OpenAPI/V1/Gift/robredgift", RequestMethod.GET);
        request.add("token", token);
        request.add("roomid", roomuid);
        request.add("red_id", gifid);
        BeautyLiveApplication.getRequestQueue().add(PAGER_JSON, request, ViewPagerOnResponse);
    }

    private OnResponseListener<JSONObject> ViewPagerOnResponse = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            L.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == PAGER_JSON) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
                Log.i("mrl", result + "这个是请求成功");
                try {
                    JSONObject data = result.getJSONObject("data");
                    final int code = result.getInt("code");
                    final int amount = data.getInt("amount");
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (code == 1) {
                                hongbaoamount.setText("手慢!红包已经被抢完了");
                                get.setVisibility(View.INVISIBLE);
                            } else {
                                hongbaoamount.setText("抢到了" + amount);
                                get.setVisibility(View.INVISIBLE);
                            }
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            L.i("lll", "请求失败了哦" + s);
        }

        @Override
        public void onFinish(int i) {
            L.i("lll", "viewpager结束了");
        }
    };
    int PAGER_JSON_TEST = 2;
    int PAGER_JSON_BAD = 3;

    //Mrl L
    public void senDanmu(String token, String roomuid, String content) {
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(Const.MAIN_HOST_URL + "/OpenAPI/V1/Gift/sendBarrage", RequestMethod.GET);
        request.add("token", token);
        request.add("roomid", roomuid);
        request.add("content", content);
        BeautyLiveApplication.getRequestQueue().add(PAGER_JSON_TEST, request, ViewPagerOnResponseDamu);
    }

    private OnResponseListener<JSONObject> ViewPagerOnResponseDamu = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            L.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == PAGER_JSON_TEST) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
                Log.i("mrl", result + "弹幕");
                try {
                    JSONObject code = result.getJSONObject("code");
                    if (code.getInt("code") != 0) {
                        handler.sendEmptyMessage(PAGER_JSON_BAD);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            L.i("lll", "请求失败了哦" + s);
            handler.sendEmptyMessage(PAGER_JSON_BAD);
        }

        @Override
        public void onFinish(int i) {
            L.i("lll", "viewpager结束了");
        }
    };


    public void aniPopupWindowValuesHolder(View view) {
        PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha",
                0f, 1f);
        PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleX",
                0, 1f);
        PropertyValuesHolder pvhZ = PropertyValuesHolder.ofFloat("scaleY",
                0, 1f);
        ObjectAnimator.ofPropertyValuesHolder(view, pvhX, pvhY, pvhZ).setDuration(1000).start();
    }

    //  时间转换类哦
    public String refFormatNowDate(long time) {
        Date nowTime = new Date(time);
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy.MM.dd");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
        return retStrFormatNowDate;
    }

    /**
     * 在会话列表中接收消息
     *
     * @param event 消息事件
     */
    public void onEvent(MessageEvent event) {
        /**
         * 接收消息类事件
         *
         * @param event 消息事件
         */
        try {
        final cn.jpush.im.android.api.model.Message msg = event.getMessage();
        L.e("lw", "我的消息" + msg);
        //若为群聊相关事件，如添加、删除群成员
        Log.i(TAG, event.getMessage().toString());
        //刷新消息
        mcontext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //收到消息的类型为单聊
                if (msg.getTargetType() == ConversationType.single) {
                    cn.jpush.im.android.api.model.UserInfo userInfo = (cn.jpush.im.android.api.model.UserInfo) msg.getTargetInfo();
                    String targetId = userInfo.getUserName();
                    String appKey = userInfo.getAppKey();
                    //判断消息是否在当前会话中
                    if (mIsSingle && targetId.equals(mTargetId)) {
                        cn.jpush.im.android.api.model.Message lastMsg = mChatAdapter.getLastMsg();
                        //收到的消息和Adapter中最后一条消息比较，如果最后一条为空或者不相同，则加入到MsgList
                        if (lastMsg == null || msg.getId() != lastMsg.getId()) {
                            mChatAdapter.addMsgToList(msg);
                        } else {
                            mChatAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });

        /**
         * 在会话列表中接收消息
         *
         * @param event 消息事件
         */
//        cn.jpush.im.android.api.model.Message msg = event.getMessage();
        Log.d(TAG, "收到消息：msg = " + msg.toString());
        ConversationType convType = msg.getTargetType();
        if (convType == ConversationType.group) {
            long groupID = ((GroupInfo) msg.getTargetInfo()).getGroupID();
            Conversation conv = JMessageClient.getGroupConversation(groupID);
            if (conv != null) {
                mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST,
                        conv));
            }
        } else {
            final cn.jpush.im.android.api.model.UserInfo userInfo = (cn.jpush.im.android.api.model.UserInfo) msg.getTargetInfo();
            final String targetID = userInfo.getUserName();
            final Conversation conv = JMessageClient.getSingleConversation(targetID, userInfo.getAppKey());
            if (conv != null&&conv.getUnReadMsgCnt()>0) {
                mUIHandler.sendEmptyMessage(UNREAD);
            }
            if (conv != null ) {
                mcontext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //如果设置了头像
                        if (!TextUtils.isEmpty(userInfo.getAvatar())) {
                            //如果本地不存在头像
                            userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                                @Override
                                public void gotResult(int status, String desc, Bitmap bitmap) {
                                    if (status == 0) {
                                        mListAdapter.addmFuImg(userInfo.getUserName().replaceAll("meilibo",""));
                                    } else {
                                        HandleResponseCode.onHandle(mcontext, status, false);
                                    }
                                }
                            });
                        }
                    }
                });
                mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST,
                        conv));
            }
        }
        }catch (Exception e){
            if (JMessageClient.getMyInfo() == null) {

                for (int i = 0; i < 5; i++) {
                    L.e("lw", "注册操作" + i);
                    register();
                    if (r = true) {
                        break;
                    }
                }
                if (r=true){
                    for (int j = 0; j < 5; j++) {
                        L.e("lw", "登录操作"+j);
                        login();
                        if (f=true) {
                            break;
                        }
                    }
                }
            }
        }
    }

    /**
     * 收到创建单聊的消息
     *
     * @param event 可以从event中得到targetID
     */
    public void onEventMainThread(Event.StringEvent event) {
        L.i("创建单聊 l", "StringEvent execute");
        try{
            String targetId = event.getTargetId();
            String appKey = event.getAppKey();
            Conversation conv = JMessageClient.getSingleConversation(targetId, appKey);
            if (conv != null) {
                mListAdapter.addNewConversation(conv);
            }
        }catch (Exception e){
            if (JMessageClient.getMyInfo() == null) {

                for (int i = 0; i < 5; i++) {
                    L.e("lw", "注册操作" + i);
                    register();
                    if (r = true) {
                        break;
                    }
                }
                if (r=true){
                    for (int j = 0; j < 5; j++) {
                        L.e("lw", "登录操作"+j);
                        login();
                        if (f=true) {
                            break;
                        }
                    }
                }
            }
        }
    }

    /**
     * 收到创建或者删除群聊的消息
     *
     * @param event 从event中得到groupID以及flag
     */
    public void onEventMainThread(Event.LongEvent event) {
        long groupId = event.getGroupId();
        Conversation conv = JMessageClient.getGroupConversation(groupId);
        if (conv != null && event.getFlag()) {
            mListAdapter.addNewConversation(conv);
        } else {
            mListAdapter.deleteConversation(groupId);
        }
    }

    /**
     * 收到保存为草稿事件
     *
     * @param event 从event中得到Conversation Id及草稿内容
     */
    public void onEventMainThread(Event.DraftEvent event) {
        String draft = event.getDraft();
        String targetId = event.getTargetId();
        String targetAppKey = event.getTargetAppKey();
        Conversation conv;
        if (targetId != null) {
            conv = JMessageClient.getSingleConversation(targetId, targetAppKey);
        } else {
            long groupId = event.getGroupId();
            conv = JMessageClient.getGroupConversation(groupId);
        }
        //如果草稿内容不为空，保存，并且置顶该会话
        if (!TextUtils.isEmpty(draft)) {
            mListAdapter.putDraftToMap(conv.getId(), draft);
            mListAdapter.setToTop(conv);
            //否则删除
        } else {
            mListAdapter.delDraftFromMap(conv.getId());
        }
    }

    @Override
    public void onDestroy() {
        isdeas=true;
        EventBus.getDefault().unregister(this);
        mcontext.unregisterReceiver(mReceiver);
        mBackgroundHandler.removeCallbacksAndMessages(null);
        mThread.getLooper().quit();

        mcontext.unregisterReceiver(receiver);
        try {
            mChatAdapter.releaseMediaPlayer();
        } catch (NullPointerException e) {
        }
        mUIHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    private class BackgroundHandler extends Handler {
        public BackgroundHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REFRESH_CONVERSATION_LIST:
                    Conversation conv = (Conversation) msg.obj;
                    mListAdapter.setToTop(conv);
                    break;
            }
        }
    }

    //    对比适配器里面的集合，和传过来的集合
    public void screenAudienList(List<AudienceInfo> oldList, List<AudienceInfo> newList, AudienceAdapter adapter) {
        //        如果观众出去了
        if (oldList.size() > newList.size()) {
            int i;
            for (i = 0; i < newList.size(); i++) {
                if (!newList.get(i).getUserId().equals(oldList.get(i).getUserId())) {
                    oldList.set(i, newList.get(i));
                    adapter.notifyItemChanged(i);
                }
            }
            while (oldList.size() > i) {
                adapter.notifyItemRemoved(i);
                oldList.remove(i);
                i++;
            }
        } else {
            int i;
            for (i = 0; i < oldList.size(); i++) {
                if (!newList.get(i).getUserId().equals(oldList.get(i).getUserId())) {
                    oldList.set(i, newList.get(i));
                    adapter.notifyItemChanged(i);
                }
            }
            while (newList.size() > i) {
                oldList.add(newList.get(i));
                adapter.notifyItemChanged(i);
                i++;
            }
        }
    }

    public void requesetRoomLoginOut() {
        wsService.sendRequest(WsObjectPool.newLogoutRequest(mRoomId));
    }

    private static class UIHandler extends Handler {
        private final WeakReference<RoomFragment> mActivity;

        public UIHandler(RoomFragment activity) {
            mActivity = new WeakReference<RoomFragment>(activity);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            RoomFragment activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case REFRESH_LAST_PAGE:
                        activity.mChatAdapter.dropDownToRefresh();
                        activity.mChatListView.onDropDownComplete();
                        if (activity.mChatAdapter.isHasLastPage()) {
                            if (Build.VERSION.SDK_INT >= 21) {
                                activity.mChatListView
                                        .setSelectionFromTop(activity.mChatAdapter.getOffset(),
                                                activity.mChatListView.getHeaderHeight());
                            } else {
                                activity.mChatListView.setSelection(activity.mChatAdapter
                                        .getOffset());
                            }
                            activity.mChatAdapter.refreshStartPosition();
                        } else {
                            activity.mChatListView.setSelection(0);
                        }
                        activity.mChatListView
                                .setOffset(activity.mChatAdapter.getOffset());
                        break;
                    case UNREAD:
                        activity.newMsg.setVisibility(View.VISIBLE);
                        break;
                    case READ:
                        activity.newMsg.setVisibility(View.GONE);
                        break;
                }
            }
        }
    }

    // 监听耳机插入
    private void initreceiver() {
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_HEADSET_PLUG);
        mcontext.registerReceiver(receiver, filter);
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent data) {
            try{
                if (data != null) {
                    //插入了耳机
                    if (data.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                        mChatAdapter.setAudioPlayByEarPhone(data.getIntExtra("state", 0));
                    }
                }
            }catch (NullPointerException e){
            }
        }
    }

    private MsgListRoomAdapter.ContentLongClickListener longClickListener = new MsgListRoomAdapter.ContentLongClickListener() {
        @Override
        public void onContentLongClick(final int position, View view) {
            Log.i(TAG, "long click position" + position);
            final cn.jpush.im.android.api.model.Message msg = mChatAdapter.getMessage(position);
            cn.jpush.im.android.api.model.UserInfo userInfo = msg.getFromUser();
            if (msg.getContentType() != ContentType.image) {
                // 长按文本弹出菜单
                String name = userInfo.getNickname();
                View.OnClickListener listener = new View.OnClickListener() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == IdHelper.getViewID(mcontext, "jmui_copy_msg_btn")) {
                            if (msg.getContentType() == ContentType.text) {
                                final String content = ((TextContent) msg.getContent()).getText();
                                if (Build.VERSION.SDK_INT > 11) {
                                    ClipboardManager clipboard = (ClipboardManager) mcontext
                                            .getSystemService(Context.CLIPBOARD_SERVICE);
                                    ClipData clip = ClipData.newPlainText("Simple text", content);
                                    clipboard.setPrimaryClip(clip);
                                } else {
                                    android.text.ClipboardManager clip = (android.text.ClipboardManager) mcontext
                                            .getSystemService(Context.CLIPBOARD_SERVICE);
                                    if (clip.hasText()) {
                                        clip.getText();
                                    }
                                }

                                Toast.makeText(mcontext, IdHelper.getString(mcontext, "jmui_copy_toast"),
                                        Toast.LENGTH_SHORT).show();
                                mDialog.dismiss();
                            }
                        } else if (v.getId() == IdHelper.getViewID(mcontext, "jmui_forward_msg_btn")) {
                            mDialog.dismiss();
                        } else {
                            mConv.deleteMessage(msg.getId());
                            mChatAdapter.removeMessage(position);
                            mDialog.dismiss();
                        }
                    }
                };
                boolean hide = msg.getContentType() == ContentType.voice;
                mDialog = DialogCreator.createLongPressMessageDialog(mcontext, name, hide, listener);
                mDialog.show();
                mDialog.getWindow().setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT);
            } else {
                String name = msg.getFromUser().getNickname();
                View.OnClickListener listener = new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (v.getId() == IdHelper.getViewID(mcontext, "jmui_delete_msg_btn")) {
                            mConv.deleteMessage(msg.getId());
                            mChatAdapter.removeMessage(position);
                            mDialog.dismiss();
                        } else if (v.getId() == IdHelper.getViewID(mcontext, "jmui_forward_msg_btn")) {
                            mDialog.dismiss();
                        }
                    }
                };
                mDialog = DialogCreator.createLongPressMessageDialog(mcontext, name, true, listener);
                mDialog.show();
                mDialog.getWindow().setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT);
            }
        }
    };

    private void dismissSoftInput() {
        if (mShowSoftInput) {
            if (mImm != null) {
                mImm.hideSoftInputFromWindow(mChatInputEt.getWindowToken(), 0);
                mShowSoftInput = false;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理发送图片，刷新界面
     *
     * @param data intent
     */
    private void handleImgRefresh(Intent data) {
        mChatAdapter.setSendImg(data.getIntArrayExtra(MsgIDs));
        mChatListView.clearFocus();
        mChatListView.post(new Runnable() {
            @Override
            public void run() {
                mChatListView.setSelection(mChatListView.getAdapter().getCount() - 1);
            }
        });
    }

    @Override
    public void onPause() {
        isdeas=true;
        RecordVoiceButton.mIsPressed = false;
        JMessageClient.exitConversation();
        Log.i(TAG, "[Life cycle] - onPause");
        super.onPause();
    }

    @Override
    public void onStop() {
        isdeas=true;
        try {
            mChatAdapter.stopMediaPlayer();
        } catch (NullPointerException e) {
        }
        if (mConv != null) {
            mConv.resetUnreadCount();
        }
        super.onStop();
    }

    @Override
    public void onResume() {
        isdeas=false;
        String targetId = mTargetId;
        if (null != targetId) {
            String appKey = mTargetAppKey;
            JMessageClient.enterSingleConversation(targetId, appKey);
        }
//        mChatAdapter.initMediaPlayer();
        Log.i(TAG, "[Life cycle] - onResume");
        super.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
            final Conversation conv = mConv;
            try {
                String originPath = mPhotoPath;
                Bitmap bitmap = BitmapLoader.getBitmapFromFile(originPath, 720, 1280);
                ImageContent.createImageContentAsync(bitmap, new ImageContent.CreateImageContentCallback() {
                    @Override
                    public void gotResult(int status, String desc, ImageContent imageContent) {
                        if (status == 0) {
                            cn.jpush.im.android.api.model.Message msg = conv.createSendMessage(imageContent);
                            Intent intent = new Intent();
                            intent.putExtra(MsgIDs, new int[]{msg.getId()});
                            handleImgRefresh(intent);
                        }
                    }
                });
            } catch (NullPointerException e) {
                Log.i(TAG, "onActivityResult unexpected result");
            }
        } else if (resultCode == RESULT_CODE_SELECT_PICTURE) {
            handleImgRefresh(data);
            //如果作为UIKit使用,去掉以下几段代码
        } else if (resultCode == RESULT_CODE_FRIEND_INFO) {
            if (mIsSingle) {
                String nickname = data.getStringExtra(NICKNAME);
                if (!TextUtils.isEmpty(nickname)) {
                    mChatTitle.setText(nickname);
                }
            }
        }
    }

    public void showAnim(int isread){
        if (isdeas){
            return;
        }
        switch (isread){
//            烟花
            case 2:
                if (fireworks==null) {
                    fireworks = new FireworksImagerView(getActivity());
                    fireworks.setGitfSpecialsStop(this);
                    RelativeLayout.LayoutParams layoutParams =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.MATCH_PARENT);
                    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                    animLayout.addView(fireworks,layoutParams);
                    fireworks.initAnim();
                }else {
                    fireworks.initAnim();
                }
                break;
//            砖石
            case 3:
                if (gen==null){
                    gen=new GenView(getActivity());
                    gen.setAnimsopt(this);
                    RelativeLayout.LayoutParams layoutParams =new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
                    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                    animLayout.addView(gen,layoutParams);
                }else {
                    gen.startAnim();
                }
                break;
//            汽车
            case 4:
                if (car==null){
                    car=new CarView(getActivity());
                    car.setAnimsopt(this);
                    animLayout.addView(car);
                    car.initAnim(animLayout.getMeasuredWidth(),animLayout.getMeasuredHeight());
                }else {
                    car.initAnim(animLayout.getMeasuredWidth(),animLayout.getMeasuredHeight());
                }
                break;
//            飞机
            case 5:
                if (plane==null) {
                    plane = new PlaneImagerView(getActivity());
                    plane.setGitfSpecialsStop(this);
                    animLayout.addView(plane);
                    plane.initAnim(getActivity().getWindowManager().getDefaultDisplay().getWidth());
                }else {
                    plane.initAnim(getActivity().getWindowManager().getDefaultDisplay().getWidth());
                }
                break;
//            游艇
            case 6:
                if (ship==null){
                    ship=new ShipView(getActivity());
                    ship.setGitfSpecialsStop(this);
                    RelativeLayout.LayoutParams layoutParams =new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    animLayout.addView(ship,layoutParams);
                    ship.initAnim(getActivity().getWindowManager().getDefaultDisplay().getWidth());
                }else {
                    ship.initAnim(getActivity().getWindowManager().getDefaultDisplay().getWidth());
                }
                break;
        }
    }

    @Override
    public void animend() {
        isgiftend=true;
        gitfSpecials.remove(0);
        if (gitfSpecials.size()>0&&isgiftend){
            isgiftend=false;
            showAnim(gitfSpecials.get(0));
        }
    }

    public void login() {
        JMessageClient.login(mMyName, mMyPassword, new BasicCallback() {
            @Override
            public void gotResult(int status, String desc) {
                if (status == 0) {
                    L.e("lw","登录成功");
                    f=true;
                } else {
                    L.e("lw","登录失败"+status+desc);
                }
            }
        });
    }

    public void register() {
        JMessageClient.register(mMyName, mMyPassword, new BasicCallback() {
            @Override
            public void gotResult(int status, String desc) {
                if (status == 0) {
                    L.e("lw","注册成功");
                    r=true;
                } else {
                    L.e("lw", "注册失败" + status + desc);
                    if (desc.equals("user exist")) {
                        r=true;
                    }
                }
            }
        });
    }

    final  int DATA_JSON=11;
    //Mrl L
    public void getDatas(String user_id) {
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(Const.WEB_BASE_URL + "user/profile", RequestMethod.GET);
        request.add("uid", user_id);
        request.add("token", LocalDataManager.getInstance().getLoginInfo().getToken());
        BeautyLiveApplication.getRequestQueue().add(DATA_JSON, request, OnResponse);
    }

    private OnResponseListener<JSONObject> OnResponse = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            Log.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == DATA_JSON) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
                try {
                    JSONObject json=result.getJSONObject("data");
                    mTestInfo=gson.fromJson(json.toString(), com.aitou.mrylive.data.bean.me.UserInfo.class);
                    cn.jpush.im.android.api.model.UserInfo userInfo;
                    for (int j=0;j<mDatas.size();j++){
                        userInfo =((cn.jpush.im.android.api.model.UserInfo) mDatas.get(j).getTargetInfo());
                        if (userInfo.getUserName().replaceAll("meilibo","").equals(mTestInfo.getId())){
                            mFuImgUrl.put(userInfo.getUserName().replaceAll("meilibo",""),mTestInfo.getAvatar());
                            break;
                        }
                    }
                    Log.i("mrs","信息"+result.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            Log.i("lll", "请求失败了哦" + s);
        }

        @Override
        public void onFinish(int i) {
            Log.i("lll", "viewpager结束了");
            count++;
            if (count==mDatas.size()) {
                handler.sendEmptyMessage(21);
            }
        }
    };


    private List<com.aitou.mrylive.data.bean.me.UserInfo> mFuDatas;
    private Gson gson;
    private com.aitou.mrylive.data.bean.me.UserInfo mTestInfo;
    private HashMap<String,String> mFuImgUrl;
    private int count;

//    拉去服务器得
    public void  initDatas(List<Conversation> data){
        mFuDatas=new ArrayList<>();
        mFuImgUrl= new HashMap<>();
        cn.jpush.im.android.api.model.UserInfo info;
        gson = new Gson();
        for (int i=0;i<data.size();i++){
            info= (cn.jpush.im.android.api.model.UserInfo) data.get(i).getTargetInfo();
            getDatas(info.getUserName().replaceAll("meilibo",""));
        }
    }


}